package com.bdqn.crm.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.bdqn.crm.config.Constants;
import com.bdqn.crm.config.shiro.MyShiroRealm;
import com.bdqn.crm.pojo.Right;
import com.bdqn.crm.pojo.Role;
import com.bdqn.crm.service.RoleService;
import jakarta.annotation.Resource;
import jakarta.servlet.ServletConnection;
import jakarta.servlet.ServletContext;
import jakarta.servlet.http.HttpServletRequest;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.mgt.RealmSecurityManager;
import org.apache.shiro.web.filter.mgt.DefaultFilterChainManager;
import org.apache.shiro.web.filter.mgt.PathMatchingFilterChainResolver;
import org.apache.shiro.web.servlet.AbstractShiroFilter;
import org.springframework.beans.BeansException;
import org.springframework.boot.web.context.WebServerApplicationContext;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import org.springframework.web.context.support.WebApplicationContextUtils;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Controller
@RequestMapping("/role")
public class RoleController {
    @Resource
    private RoleService roleService;

    public void reloadFilterChainDefinitions() {
        try {
            HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
            ServletContext servletContext = request.getSession().getServletContext();
            AbstractShiroFilter shiroFilter = (AbstractShiroFilter) WebApplicationContextUtils.getWebApplicationContext(servletContext).getBean("shiroFilter");
            synchronized (shiroFilter) {
                PathMatchingFilterChainResolver filterChainResolver = (PathMatchingFilterChainResolver) shiroFilter.getFilterChainResolver();
                DefaultFilterChainManager manager = (DefaultFilterChainManager) filterChainResolver.getFilterChainManager();
                // 清空老的权限控制
                manager.getFilterChains().clear();
                // 加载权限控制
                Map<String, String> chains = roleService.loadFilterChainDefinitions();
                for (Map.Entry<String, String> entry : chains.entrySet()) {
                    String url = entry.getKey();
                    String chainDefinition = entry.getValue().trim().replace(" ", "");
                    manager.createChain(url, chainDefinition);
                }
                System.out.println("更新权限成功");
            }
        } catch (BeansException e) {
            throw new RuntimeException(e);
        }
    }

    @RequestMapping(value = "/list")
    public String list(@RequestParam(required = false,defaultValue = "") String roleName, @RequestParam(defaultValue = "1") Integer pageIndex, Model model){
        Sort sort=Sort.by(Sort.Direction.DESC,"roleId");
        Pageable pageable=PageRequest.of(pageIndex-1,3,sort);
        Page<Role> rolePage=roleService.findRole(roleName,pageable);
        model.addAttribute("rolePage",rolePage);
        model.addAttribute("roleName",roleName);//保存查询条件
        return "role/list";
    }
    @RequestMapping(value ="/add")
    public String add(Model model){
        //查询所有权限
        List<Right> rights=roleService.finAllRights();
        model.addAttribute("rights",rights);
        return "role/add";
    }

    @RequestMapping(value = "/edit")
    public String edit(Long roleId,Model model){
        Role role=roleService.getRole(roleId);
        model.addAttribute("role",role);
        //查询角色的权限
        List<Right> roleRights=roleService.findRightsByRole(role);
        model.addAttribute("roleRights",roleRights);
        //查询所有权限
        List<Right> rights=roleService.finAllRights();
        model.addAttribute("rights",rights);
        return "role/edit";
    }
    @RequestMapping(value = "/save")
    public String save(Role role,String[] rightCodes){
        if (rightCodes!=null){
            for (String rightCode : rightCodes) {
                Right right=new Right();
                right.setRightCode(rightCode);
                role.getRights().add(right);//将关联的权限添加到角色中，用于级联新增关联表的数据
            }
        }
        roleService.saveRole(role);
        RealmSecurityManager rsm = (RealmSecurityManager) SecurityUtils.getSecurityManager();
        MyShiroRealm realm = (MyShiroRealm) rsm.getRealms().iterator().next();
        realm.clearAllCachedAuthorizationInfo();
        return "redirect:/role/list";//增删改之后跳转最后使用重定向
    }
    @RequestMapping(value = "/del")
    @ResponseBody//返回json
    public Map del(Long roleId){
        Map map=new HashMap();
        try {
            roleService.deleteRoleById(roleId);
            map.put("delResult","true");
        }catch (Exception e){
            e.printStackTrace();
            map.put("delResult","false");
        }
        return map;
    }

    @RequestMapping("/list")
    public String list(Model model, String roleName, @RequestParam(defaultValue = "1") Integer pageIndex){
        QueryWrapper<Role> qw=new QueryWrapper<>();
        if(roleName!=null && !"".equals(roleName)){
            qw.like("role_name",roleName);
        }
        Page<Role> rolePage= new Page<>(pageIndex, Constants.ROLE_PAGE_SIZE);
        IPage<Role> rolePager = roleService.page(rolePage,qw);
        model.addAttribute("roleName",roleName);
        model.addAttribute("rolePager",rolePager);
        return "role/list";
    }
}
